package org.cfd.controller;

import jakarta.annotation.Resource;
import java.util.Date;
import org.cfd.entity.EvaluationInput;
import org.cfd.entity.EvaluationUpdateInput;
import org.cfd.entity.Evaluations;
import org.cfd.service.EvaluationsService;
import org.cfd.utils.Code;
import org.cfd.utils.Result;
import org.springframework.web.bind.annotation.*;

/**
 * 评价Controller
 *
 * @author rjs
 */
@CrossOrigin
@RestController
@RequestMapping("/evaluations")
public class EvaluationsController {

  @Resource private EvaluationsService evaluationsService;

  /**
   * 通过评价ID查询评价
   *
   * @param id 评价ID
   * @return 查询到的评价
   */
  @GetMapping("/{id}")
  public Result getEvaluation(@PathVariable("id") Integer id) {
    Evaluations evaluations = evaluationsService.getById(id);
    if (evaluations != null) {
      return new Result(Code.SELECT_SUCCESS, "查询成功", evaluations);
    } else {
      return new Result(Code.SELECT_ERROR, "查询失败");
    }
  }

  /**
   * 创建评价
   *
   * @param input 创建评价所需的参数
   * @return 创建的评价
   */
  @PostMapping
  public Result createEvaluation(@RequestBody EvaluationInput input) {
    Evaluations evaluations = new Evaluations();
    evaluations.setUserId(input.getUserId());
    evaluations.setProductId(input.getProductId());
    evaluations.setRating(input.getRating());
    evaluations.setComment(input.getComment());
    evaluationsService.save(evaluations);
    return new Result(Code.ADD_SUCCESS, "创建成功", evaluations);
  }

  /**
   * 更新评价
   *
   * @param id 评价ID
   * @param input 更新评价所需的参数
   * @return 更新成功返回true，否则返回false
   */
  @PutMapping("/{id}")
  public Result updateEvaluation(
      @PathVariable("id") Integer id, @RequestBody EvaluationUpdateInput input) {
    Evaluations evaluations = evaluationsService.getById(id);
    if (evaluations != null) {
      evaluations.setRating(input.getRating());
      evaluations.setComment(input.getComment());
      evaluations.setUpdatedAt(new Date());
      return new Result(Code.UPDATE_SUCCESS, "更新成功", evaluations);
    }
    return new Result(Code.UPDATE_ERROR, "更新失败");
  }

  /**
   * 删除评价
   *
   * @param id 评价ID
   * @return 删除成功返回true，否则返回false
   */
  @DeleteMapping("/{id}")
  public Result deleteEvaluation(@PathVariable("id") Integer id) {
    boolean removed = evaluationsService.removeById(id);
    if (removed) {
      return new Result(Code.DELETE_SUCCESS, "删除成功");
    } else {
      return new Result(Code.DELETE_ERROR, "删除失败");
    }
  }
}
